import * as fileApi from '@/api/file'
import { defineStore } from 'pinia'
import OSS from 'ali-oss'
export const useFileStore = defineStore('file', {
  state: () => ({
    client: null,
  }),
  getters: {},
  actions: {
    async getFileInfo() {
      const { data } = await fileApi.getInfo()
      const { region, accessKeyId, accessKeySecret, bucket, securityToken: stsToken } = data
      this.client = new OSS({
        endpoint: region,
        accessKeyId,
        accessKeySecret,
        bucket,
        stsToken,
      })
    },
    async upload(name, file, size, callBack) {
      name = name.replace(/[(]/g, '（').replace(/[)]/g, '）')
      if (!this.client) {
        await this.getFileInfo()
      }
      const now = Date.now()
      const fix = `media_project/${now}-`
      // 大于100mb分片上传
      if (size >= 2 ** 20 * 100) {
        return this.client
          .multipartUpload(`${fix}${name}`, file, {
            mime: 'text/plain',
            parallel: 4,
            partSize: 1024 * 1024,
            progress: (p, cpt, res) => {
              // console.log(p, cpt, res)
              if (typeof callBack === 'function') {
                callBack(p, cpt, res)
              }
            },
          })
          .then(({ name }) => ({ fileName: name.replace(fix, ''), fileUrl: name }))
          .catch(() => {
            this.client = null
            $message.warning(`上传异常请重试!`)
          })
        // 小于100mb简单上传
      } else {
        return this.client
          .put(`${fix}${name}`, file, {
            mime: 'json',
            headers: { 'Content-Type': 'text/plain' },
          })
          .then(({ name }) => ({ fileName: name.replace(fix, ''), fileUrl: name }))
          .catch(() => {
            this.client = null
            $message.warning(`上传异常请重试!`)
          })
      }
    },
    async getUrl(filename, fileUrl) {
      if (!this.client) {
        await this.getFileInfo()
      }
      try {
        return this.client.signatureUrl(fileUrl, {
          response: {
            'content-disposition': 'attachment; filename="' + filename + '"',
          },
        })
      } catch (error) {
        this.client = null
        $message.warning(`路径异常请重试!`)
      }
    },
  },
})
